import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:homepad/iot/nova_config.dart';
import 'package:homepad/models/datetime_model.dart';
import 'package:homepad/models/nova_model.dart';
import 'package:homepad/models/weather_model.dart';
import 'package:homepad/models/websocket_client.dart';
import 'package:homepad/screens/home.dart';
import 'package:homepad/screens/panel_control.dart';
import 'package:homepad/screens/panel_service.dart';
import 'package:homepad/styles.dart';
import 'package:provider/provider.dart';
import 'package:go_router/go_router.dart';

import 'logger/logger.dart';

GoRouter router() => GoRouter(initialLocation: "/", routes: [
      GoRoute(path: "/", builder: (context, state) => const PageHome()),
      GoRoute(path: "/services", builder: (context, state) => const PanelService()),
      GoRoute(path: "/control", builder: (context, state) => const PanelControl()),
    ]);

class MyApp extends StatelessWidget {
  final NovaConfig config;

  const MyApp({super.key, required this.config});

  @override
  Widget build(BuildContext context) {
    final provider = MultiProvider(
      providers: [
        ChangeNotifierProvider<DateTimeModel>(create: (_) => DateTimeModel()),
        Provider(create: (_) => WebsocketClient()),
        ChangeNotifierProxyProvider<WebsocketClient, NovaModel>(
            create: (context) => NovaModel(config: config),
            update: (context, client, nova) {
              if (nova == null) throw ArgumentError.notNull("Nova");
              nova.client = client;
              client.delegate = nova;
              return nova;
            }),
        ChangeNotifierProvider<WeatherModel>(create: (_) => WeatherModel()),
      ],
      child: MaterialApp.router(
        debugShowCheckedModeBanner: false,
        theme: ThemeData.light().copyWith(extensions: <ThemeExtension<dynamic>>[
          MyStyles(),
        ]),
        color: Colors.black,
        routerConfig: router(),
      ),
    );

    return !logger.isWeb
        ? provider
        : Container(
            color: Colors.black,
            alignment: Alignment.center,
            child: Container(
              height: 600,
              width: 1024,
              decoration: BoxDecoration(
                border: Border.all(
                    width: 2,
                    strokeAlign: BorderSide.strokeAlignOutside,
                    color: const Color.fromARGB(50, 255, 255, 255)),
                color: Colors.black
              ),
              child: provider,
            ),
          );
  }
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // final data = await rootBundle.loadString("assets/homepad_config.json");
  final data = await rootBundle.loadString("assets/radxa_config.json");
  final map = jsonDecode(data) as Map<String, dynamic>;
  final config = NovaConfig.fromJson(map);

  runApp(MyApp(config: config));
}
